package com.buildings.activity.map;

import android.Manifest;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.webkit.GeolocationPermissions;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;
import com.buildings.R;
import com.buildings.activity.TownHouseFormActivity;
import com.buildings.activity.TownNonHouseFormActivity;
import com.buildings.activity.form.NewProjectFormActivity;
import com.buildings.activity.reinforce.HouseReinforceFormActivity;
import com.buildings.api.Api;
import com.buildings.base.BaseActivity;
import com.buildings.bean.ReinforceListResult;
import com.buildings.bean.ReinforceResult;
import com.buildings.http.BaseCallBack;
import com.buildings.http.MyHttpClient;
import com.buildings.permissions.Acp;
import com.buildings.permissions.AcpListener;
import com.buildings.permissions.AcpOptions;
import com.buildings.util.CustomToast;
import com.buildings.util.DialogUtils;
import java.io.IOException;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import okhttp3.Call;

import static com.buildings.activity.TaskMapActivity.FROM_TASK_MAP;

/**
 * @author shiyaolei
 * @packager com.buildings.activity.map
 * @date 2020/9/7
 **/
public class ReinforceMapActivity extends BaseActivity implements View.OnClickListener {

  private WebView webView;
  private String mapInfo;//地图范围面积 // 95.72929,39.82741;98.80546,39.42123;97.0916,38.53302;
  private String taskId;
  private String taskName;
  private String status;

  private int pageNum = 1;//当前请求页数
  private int pageSize = 100000;
  private Dialog dialog;

  private List<ReinforceResult.ReinforceData> result;

  private Timer timer;

  @Override protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_map);
    askMultiPermission();
  }

  public void initView() {
    mapInfo = getIntent().getStringExtra("mapInfo");
    taskId = getIntent().getStringExtra("taskId");
    taskName = getIntent().getStringExtra("taskName");
    status = getIntent().getStringExtra("status");
    //        mapInfo = "116.2788,40.14234;116.28189,40.14357;116.27973,40.14009";

    TextView title = findViewById(R.id.tv_title);
    title.setText("选择建筑物");
    findViewById(R.id.iv_back).setOnClickListener(this);
    webView = findViewById(R.id.webview);
    webView.setHorizontalScrollBarEnabled(false);//水平不显示
    webView.setVerticalScrollBarEnabled(false); //垂直不显示
    WebSettings webSettings = webView.getSettings();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
      webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
    }
    webSettings.setJavaScriptEnabled(true);//启用js
    webSettings.setBlockNetworkImage(false);//解决图片不显示
    webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
    webSettings.setDomStorageEnabled(true);
    webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
    webView.getSettings().setAllowFileAccessFromFileURLs(true);
    webView.getSettings().setGeolocationDatabasePath(getFilesDir().getPath());
    webSettings.setDatabaseEnabled(true);//
    webSettings.setGeolocationEnabled(true);//
    webView.addJavascriptInterface(new ReinforceMapActivity.MyJavaInterface(), "androidObject");
    //支持缩放，默认为true。
    webSettings.setSupportZoom(false);
    //        webSettings.setBuiltInZoomControls(true);
    //调整图片至适合webview的大小
    webSettings.setUseWideViewPort(false);
    // 缩放至屏幕的大小
    webSettings.setLoadWithOverviewMode(false);
    //设置默认编码
    webSettings.setDefaultTextEncodingName("utf-8");
    ////设置自动加载图片
    webSettings.setLoadsImagesAutomatically(true);

    webView.setWebViewClient(new WebViewClient() {
      @Override public boolean shouldOverrideUrlLoading(WebView view, String url) {
        view.loadUrl(url);
        return true;
      }

      @Override public void onReceivedError(WebView view, WebResourceRequest request,
          WebResourceError errorResponse) {
        super.onReceivedError(view, request, errorResponse);
      }

      @Override public void onReceivedError(WebView view, int errorCode, String description,
          String failingUrl) {
        super.onReceivedError(view, errorCode, description, failingUrl);
        //6.0以下执行
        //网络未连接
      }

      @Override public void onPageFinished(WebView view, String url) {
        super.onPageFinished(view, url);
        //116.2788,40.14234   116.28189,40.14357  116.27973,40.14009  116.28284,40.14071
        if (!TextUtils.isEmpty(mapInfo)) {
          String[] array = mapInfo.split(";");
          if (!TextUtils.isEmpty(array[0])) {
            String[] lnglat = array[0].split(",");
            String centerParams = "'" + lnglat[0] + "','" + lnglat[1] + "'";
            webView.loadUrl("javascript:centerAndZoom(" + centerParams + ")");
          }
          String params = "'" + mapInfo + "'";
          //String params = "'116.2788','40.14234','116.28189','40.14357','116.28284','40.14071','116.27973','40.14009'";
          webView.loadUrl("javascript:onRange(" + params + ")");
        }
        //开始调用获取表单列表接口
        dialog = DialogUtils.showRefreshDialog(activity);
        //4 表示全部
        getReinforceList();
      }

      @Override public void onPageStarted(WebView view, String url, Bitmap favicon) {
        super.onPageStarted(view, url, favicon);
      }
    });
    webView.setWebChromeClient(new WebChromeClient() {
      @Override public void onReceivedTitle(WebView view, String title) {
        super.onReceivedTitle(view, title);
      }

      public void onGeolocationPermissionsShowPrompt(String origin,
          GeolocationPermissions.Callback callback) {
        callback.invoke(origin, true, false);
      }
    });
    webView.loadUrl("file:///android_asset/map.html");
    //        webView.loadUrl("file:///android_asset/images/map.html");

    //实时定位
    startLocation();
  }

  private void askMultiPermission() {
    Acp.getInstance(this).
        request(new AcpOptions.Builder().setPermissions(
            //                                        Manifest.permission.CAMERA,
            Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE,
            //                               Manifest.permission.RECEIVE_SMS,
            Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION
            //                                        Manifest.permission.RECORD_AUDIO
        ).build(), new AcpListener() {
          @Override public void onGranted() {
            initView();
            //                                geocodeLocation();
          }

          @Override public void onDenied(List<String> permissions) {

          }
        });
  }

  private void startLocation() {

    timer = new Timer();
    timer.schedule(new TimerTask() {
      @Override public void run() {
        activity.runOnUiThread(new Runnable() {
          @Override public void run() {
            webView.loadUrl("javascript:setPhoneLocation()");
            // Log.e("startLocation","timer------");
          }
        });
      }
    }, 1000, 5000);
  }

  Handler handler = new Handler() {
    @Override public void handleMessage(Message msg) {
      super.handleMessage(msg);
      double[] a = (double[]) msg.obj;
      //            webView.loadUrl("javascript:addMarker("+a[1]+","+a[0]+")");
    }
  };

  @Override public void onClick(View v) {
    switch (v.getId()) {
      case R.id.iv_back:
        finish();
        break;
    }
  }

  public class MyJavaInterface {

    @JavascriptInterface public void androidMarkerClick(String lng, String lat) {
      Log.e("androidMarkerClick经纬度", lng + "," + lat);
      //点击标注
      if (result != null) {
        for (ReinforceResult.ReinforceData bean : result) {
          //遍历集合，查找经纬度相同的对象，就是所点击的表单建筑
          if (TextUtils.equals(lng, bean.longitude) && TextUtils.equals(lat, bean.latitude)) {
            //跳转到表单详情，判断是否可以编辑
            startForm(bean);
            return;
          }
        }
      }
    }

    @JavascriptInterface public void androidMapClick(String lng, String lat) {
      Log.e("点击的经纬度", lng + "," + lat);
      androidMapClick(lng, lat, "", "");
    }

    @JavascriptInterface
    public void androidMapClick(final String lng, final String lat, final String locationLng,
        final String locationLat) {
      //横竖屏切换  0竖屏   1横屏 somehowTheScreen
      Log.e("经纬度", lng + "," + lat);
      runOnUiThread(new Runnable() {
        @Override public void run() {
          if (!TextUtils.equals(status, "2")) {
            //dialog选择建筑类型
            DialogUtils.showReinforceDialog(activity, new View.OnClickListener() {
              @Override public void onClick(View v) {
                int type = (int) v.getTag();
                Intent intent = null;
                String iconUrl = "";
                switch (type) {
                  case 1:
                    //城镇住宅
                    iconUrl = "images/ic_town_house.png";
                    break;
                  case 2:
                    //城镇非住宅
                    iconUrl = "images/ic_town_no_house.png";
                    break;
                }
                //此处请求接口，新的表单
                ReinforceResult.ReinforceData data = new ReinforceResult.ReinforceData();
                data.latitude = lat;
                data.longitude = lng;
                data.title = taskName;
                data.status="0";
                data.projectType = type == 1 ? "0" : "1";
                startForm(data);
              }
            }, true);
          }
        }
      });
    }
  }


  @Override
  protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if(requestCode == 1000 && resultCode == RESULT_OK){
      if(dialog != null){
        dialog.show();
      }
      webView.loadUrl("javascript:centerAndZoom('1','1')");
      getReinforceList();
    }
  }

  private void getReinforceList() {
    String host = Api.REINFORCE + "page?projectType=&curPage=1&pageSize=" + pageSize;

    MyHttpClient.newBuilder()
        .get()
        .url(host)
        .build()
        .enqueue(new BaseCallBack<ReinforceListResult>() {
          @Override public void onSuccess(ReinforceListResult bean) {
            super.onSuccess(bean);
            if (bean.getCode() == 200 && bean.data != null) {
              result = bean.data.rows;
              for (ReinforceResult.ReinforceData formBean : result) {
                //往地图上添加对应的表单
                String lng = formBean.longitude;
                String lat = formBean.latitude;
                String buildType = formBean.projectType;
                String iconUrl = "";
                //0、城镇住宅1、城镇非住宅，2、农村住房，3、农村公共住宅
                if (TextUtils.equals("0", buildType)) {
                  //城镇住宅 "images/ic_village_public_build.png";
                  if (TextUtils.equals("0", formBean.status)) { //表单状态  0未提交  1未审核  2审核未通过 3审核通过
                    //未提交
                    iconUrl = "images/reinforce_no.png";
                  } else if (TextUtils.equals("1", formBean.status)) {
                    //未审核
                    iconUrl = "images/reinforce_yes.png";
                  }
                  if (TextUtils.equals("2", formBean.status)) {
                    //审核未通过
                    iconUrl = "images/reinforce_no.png";
                  }
                  if (TextUtils.equals("3", formBean.status)) {
                    //审核成功
                    iconUrl = "images/reinforce_yes.png";
                  }
                } else if (TextUtils.equals("1", buildType)) {
                  //城镇非住宅
                  if (TextUtils.equals("0", formBean.status)) { //表单状态  0未提交  1未审核  2审核未通过 3审核通过
                    //未提交
                    iconUrl = "images/new_projcect_no.png";
                  } else if (TextUtils.equals("1", formBean.status)) {
                    //未审核
                    iconUrl = "images/new_projcet_yes.png";
                  }
                  if (TextUtils.equals("2", formBean.status)) {
                    //审核未通过
                    iconUrl = "images/new_projcect_no.png";
                  }
                  if (TextUtils.equals("3", formBean.status)) {
                    //审核成功
                    iconUrl = "images/new_projcet_yes.png";
                  }
                }
                //                                iconUrl = "images/ic_town_no_house.png";
                webView.loadUrl(
                    "javascript:addIconMarker('" + lng + "','" + lat + "','" + iconUrl + "')");
              }
            } else {
              CustomToast.showToast(activity, "获取加固工程信息失败");
            }
            if (dialog != null) {
              dialog.dismiss();
            }
          }

          @Override public void onFailure(Call call, IOException e) {
            super.onFailure(call, e);
            CustomToast.showToast(activity, "网络异常");
            if (dialog != null) {
              dialog.dismiss();
            }
          }

          @Override public void onError(int code) {
            super.onError(code);
            CustomToast.showToast(activity, "网络异常");
            if (dialog != null) {
              dialog.dismiss();
            }
          }
        });
  }

  private void startForm(ReinforceResult.ReinforceData data) {
    if (data == null) {
      return;
    }

    data.title = taskName;
    String projectType = data.projectType;

    if (TextUtils.equals(projectType, "0")) {
      HouseReinforceFormActivity.intentHouseReinforceFormActivity(this, data, FROM_TASK_MAP);
    } else if (TextUtils.equals(projectType, "1")) {
      NewProjectFormActivity.intentNewProjectFormActivity(this, data, FROM_TASK_MAP);
    }
  }
}
